package db

import (
	"fmt"
	"pan/db/mysql"
)

// UserFile: 用户文件结构体
type UserFile struct {
	UserName   string
	FileHash   string
	FileName   string
	FileSize   int64
	UploadAt   string
	LastUpdate string
}

// OnUserFileUploadFinished: 上传完成保存文件meta信息到用户文件表
func OnUserFileUploadFinished(username, fileHash, fileName string, fileSize int64) bool {
	sql := `INSERT IGNORE INTO user_file
	(file_hash,
	file_name,
	file_size,
	user_name)
	VALUES
	(?,
	?,
	?,
	?);`
	stmt, err := mysql.DBConn().Prepare(sql)
	if err != nil {
		fmt.Printf("prepare insert user_file sql fail err:%s\n", err.Error())
		return false
	}
	defer stmt.Close()
	_, err = stmt.Exec(fileHash, fileName, fileSize, username)
	if err != nil {
		fmt.Printf("excute insert user_file sql fail err:%s\n", err.Error())
		return false
	}
	return true
}

// QueryUserFileMetas: 获取用户文件信息
func QueryUserFileMetas(username string, limit int) ([]UserFile, error) {
	sql := `
		SELECT file_hash, file_name, file_size, upload_at, last_update
		FROM user_file
		WHERE user_name = ?
		LIMIT ?
	`
	stmt, err := mysql.DBConn().Prepare(sql)
	if err != nil {
		return nil, err
	}
	// fmt.Println(username, limit)
	defer stmt.Close()
	rows, err := stmt.Query(username, limit)
	if err != nil {
		return nil, err
	}
	var userFiles []UserFile
	for rows.Next() {
		userFile := UserFile{}
		err = rows.Scan(&userFile.FileHash, &userFile.FileName, &userFile.FileSize, &userFile.UploadAt, &userFile.LastUpdate)
		if err != nil {
			fmt.Println(err)
			break
		}
		userFiles = append(userFiles, userFile)
	}
	return userFiles, nil
}
